# -*- coding: utf-8 -*-
# @Time    : 2018-05-15 15:21
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : CreditCnt.py
# @Software: PyCharm

'''eof
name:贷款及其他账户总数
code:CreditCnt
tableName:
columnName:
groups:个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import json
reload(sys)
sys.setdefaultencoding('utf-8')


def FormatData(tableName):
    try:
        # icr是最外面一层表里面的
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def ConvertDataType(dataValue, dataType):
    returnData = None
    if dataType == 'float':
        try:
            returnData = float(dataValue) if float(dataValue) >= 0 else None
        except:
            returnData = None
    elif dataType == 'None':
        returnData = 0 if dataValue is None else dataValue
    return returnData




def CreditCnt():
    try:
        # 未结清贷款信息汇总
        icrUnpaidLoan = FormatData("ICRUnpaidLoan")
        # 贷记卡信息
        icrUndestoryLoancard = FormatData("ICRLoancardInfo002*Card")
        # 准贷记卡信息
        icrUndestoryStandardLoancard = FormatData("ICRStdLoancardInfo002*Std")

        if icrUnpaidLoan == [{}] and icrUndestoryLoancard == [{}] and icrUndestoryStandardLoancard == [{}]:
            return u'缺失值'
        else:
            # 未结清贷款笔数
            accountCountL = ConvertDataType(icrUnpaidLoan[0].get('AccountCount'), 'float')
            returnlist1 = []
            returnlist2 = []
            #贷记卡信息-币种
            for icrLoanInfo002Loan in icrUndestoryLoancard:
                try:
                    LoancardCurrency = icrLoanInfo002Loan.get('Currency')
                    #贷记卡信息-账户状态
                    Loancardstate = icrLoanInfo002Loan.get('State')
                    if ( LoancardCurrency == u'人民币') and (Loancardstate in [u'止付',u'冻结',u'呆账',u'正常']):
                        returnlist1.append(Loancardstate)
                except:
                    returnlist1.append(None)
            for icrLoanInfo002Loan1 in icrUndestoryStandardLoancard:
                try:
                    #准贷记卡信息-币种
                    StandardLoancardCurrency = icrLoanInfo002Loan1.get('Currency')
                     #准贷记卡信息-账户状态
                    Standardloancardstate = icrLoanInfo002Loan1.get('State')
                    if StandardLoancardCurrency == u'人民币' and Standardloancardstate in [u'止付',u'冻结',u'呆账',u'正常']:
                        returnlist2.append(Standardloancardstate)
                except:
                    returnlist2.append(None)
        if accountCountL is None and returnlist1 is None and returnlist2 is None:
            return u'缺失值'
        return ConvertDataType(accountCountL, 'None')+len(returnlist1)+len(returnlist2)
    except:
        return u'缺失值'

result = CreditCnt()
